package com.cqfae.deploycentral.app.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqfae.deploycentral.app.config.TestLinkInfo;
import com.cqfae.deploycentral.app.dao.entity.ReportInfo;
import com.cqfae.deploycentral.app.dao.entity.ReportTestLink;
import com.cqfae.deploycentral.app.dao.mapper.ReportTestLinkMapper;
import com.cqfae.deploycentral.app.job.JiraJob;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;


@Component
public class QuartzUtil {

    private static Logger logger = LoggerFactory.getLogger(JiraJob.class);

    private QuartzUtil() {
        super();
    }

    /**
     * 获取上下文
     *
     * @param context
     * @return
     */
    public static ApplicationContext getApplicaitonContext(JobExecutionContext context) {
        try {
            return (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
        } catch (SchedulerException e) {
            logger.error(" QuartzUtil.JobExecutionContext SchedulerException ", e);
            return null;
        }
    }

    /**
     * 设置ReportInfo数据
     *
     * @param reportCode
     * @param entity
     * @param sitBugMsg
     * @param regBugMsg
     * @param reportTestLinkMapper
     */
    public static void setReportInfo(String reportCode, ReportInfo entity, String sitBugMsg, String regBugMsg, ReportTestLinkMapper reportTestLinkMapper) {
        // 获取数据
        ReportTestLink reportTestLink = new ReportTestLink();
        reportTestLink.setReportCode(reportCode);
        List<ReportTestLink> reportTestLinkList = reportTestLinkMapper.select(reportTestLink);
        StringBuilder sitSB = new StringBuilder();
        StringBuilder regSB = new StringBuilder();
        if (reportTestLinkList != null && !reportTestLinkList.isEmpty()) {
            for (ReportTestLink reportTestLink1 : reportTestLinkList) {
                sitSB = setSitSB(sitSB, sitBugMsg, reportTestLink1);
                regSB = setRegSB(regSB, regBugMsg, reportTestLink1);
            }
        }
        entity.setSitResult(sitSB.toString());
        entity.setRetResult(regSB.toString());
        entity.setUpdateTime(new Date());
    }

    /**
     * 设置sit信息
     *
     * @param sitSB
     * @param sitBugMsg
     * @param reportTestLink
     * @return
     */
    private static StringBuilder setSitSB(StringBuilder sitSB, String sitBugMsg, ReportTestLink reportTestLink) {
        if (StringUtils.isNotBlank(sitSB.toString())) {
            sitSB.append("\n");
        }
        if (StringUtils.isNotBlank(reportTestLink.getSitResult())) {
            sitSB.append(reportTestLink.getSitResult());
        }
        String sitBugMsgStr;
        if (reportTestLink.getSitBugCount() != null) {
            sitBugMsgStr = MessageFormat.format(sitBugMsg, reportTestLink.getSitBugCount());
        } else {
            sitBugMsgStr = MessageFormat.format(sitBugMsg, "0");
        }
        sitSB.append(sitBugMsgStr);
        return sitSB;
    }

    /**
     * 设置reg信息
     *
     * @param regSB
     * @param regBugMsg
     * @param reportTestLink
     * @return
     */
    private static StringBuilder setRegSB(StringBuilder regSB, String regBugMsg, ReportTestLink reportTestLink) {
        if (StringUtils.isNotBlank(regSB.toString())) {
            regSB.append("\n");
        }
        if (StringUtils.isNotBlank(reportTestLink.getRegResult())) {
            regSB.append(reportTestLink.getRegResult());
        }
        String regBugMsgStr;
        if (reportTestLink.getRegBugCount() != null) {
            regBugMsgStr = MessageFormat.format(regBugMsg, reportTestLink.getRegBugCount());
        } else {
            regBugMsgStr = MessageFormat.format(regBugMsg, "0");
        }
        regSB.append(regBugMsgStr);
        return regSB;
    }

    /**
     * @param restTemplate
     * @param testLinkInfo
     * @param tprjname
     * @param testplanId
     * @return
     */
    public static String getTestplanName(RestTemplate restTemplate, TestLinkInfo testLinkInfo, String tprjname, String testplanId) {
        // 访问url获取数据
        String url = testLinkInfo.getHost() + testLinkInfo.getGetprojecttestplans() + tprjname;
        logger.info("ReportInfoServiceImpl.getTestPlan call url:{}", url);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url,
                HttpMethod.POST, null, String.class);
        String responseEntityStr = GsonUtils.getInstance().toJson(responseEntity);
        logger.info("ReportInfoServiceImpl.getTestPlan return result:{}", responseEntityStr);
        String bodyStr = responseEntity.getBody();
        JSONObject bodyJson = JSONObject.parseObject(bodyStr);
        String testplanName = "";
        // 数据转换
        if (bodyJson != null && !bodyJson.isEmpty()) {
            JSONArray bodyJsonArray = (JSONArray) bodyJson.get("testplans");
            if (bodyJsonArray != null && !bodyJsonArray.isEmpty()) {
                for (int i = 0; i < bodyJsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) bodyJsonArray.get(i);
                    String code = String.valueOf(jsonObject.get("id"));
                    String name = String.valueOf(jsonObject.get("name"));
                    if (code.equalsIgnoreCase(testplanId)) {
                        testplanName = name;
                    }
                }
            }
        }
        return testplanName;
    }

}
